﻿using EFFC.Frame.Net.Module.Extend.EWRA.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFFC.Extends.LinqDLR2SQL;
using EFFC.Frame.Net.Unit.DB;
using EFFC.Frame.Net.Base.Data.Base;
using EFFC.Frame.Net.Module.Extend.EWRA.Attributes.Validation;
using EFFC.Frame.Net.Base.Common;
using EFFC.Frame.Net.Base.Data;
using EFFC.Frame.Net.Module.Business.Datas;
using ICPFrameLib.Business;
using ICPFrameLib.Attributes;
using EFFC.Frame.Net.Unit.DB.Parameters;

namespace XHRPMIS.Business.v1._0
{
    public class DictionarySet : MyRestLogic
    {
        [EWRARoute("get", "/dictionaryset/pop/{name}")]
        [EWRARouteDesc("获取指定词典表中的数据列表")]
        [EWRAAddInput("name", "string", "表名", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
istree:'bool类型的值，是否为树结构数据集',
data:[结果集]
}")]
        object PopSelect(string name)
        {
            return get(name);
        }
        [ActionAuth("DictionaryTable")]
        [EWRARouteDesc("获取指定词典表中的数据列表")]
        [EWRAAddInput("id", "string", "表uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
istree:'bool类型的值，是否为树结构数据集',
data:[结果集]
}")]
        public override object get(string id)
        {
            SetCacheEnable(false);
            var metaup = DB.NewMetaUnitParameter();
            var up = DB.NewDBUnitParameter();
            var s = from t in DB.LamdaTable(metaup, "EXTEND_DICTIONARY_TABLE", "a")
                    where (t.dic_uid == id || t.dic_name == id) && t.IsCreated == 1
                    select t;
            var list = s.GetQueryList(metaup);
            if (list.Count <= 0)
            {
                return new
                {
                    code = "failed",
                    msg = "词典表不存在",
                };
            }
            dynamic info = list.First();
            string tablename = info.dic_name;
            var data = (from t in DB.LamdaTable(up, tablename, "a")
                        orderby t.sort_no
                        select t).GetQueryList(up);

            return new
            {
                code = "success",
                msg = "",
                istree = BoolStd.IsNotBoolThen(info.istree),
                data = data
            };
        }
        [ActionAuth("DictionaryTable")]
        [EWRAEmptyValid("id,data")]
        [EWRARouteDesc("新增词典表中的数据")]
        [EWRAAddInput("id", "string", "元数据表uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAAddInput("data", "array", @"待新增的数据列表，格式:
[
{
    code:'值',
    value:'值',
    level:'树结构中的层级,只有istree==true时候才有栏位',
    p_code:'父节点编号,只有istree==true时候才有栏位',
    sort_no:'排序'
}
]", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        public override object post()
        {
            var uid = ComFunc.nvl(PostDataD.id);
            var data = PostDataD.data;
            if (!(data is IEnumerable<object>))
            {
                return new
                {
                    code = "failed",
                    msg = "数据格式不正确"
                };
            }
            var metaup = DB.NewMetaUnitParameter();
            var up = DB.NewDBUnitParameter();

            var s = from t in DB.LamdaTable(metaup, "EXTEND_DICTIONARY_TABLE", "a")
                    where (t.dic_uid == uid || t.dic_name == uid) && t.IsCreated == 1
                    select t;
            var list = s.GetQueryList(metaup);
            if (!(from t in DB.LamdaTable(metaup, "EXTEND_DICTIONARY_TABLE", "a")
                  where (t.dic_uid == uid || t.dic_name == uid) && t.IsCreated == 1
                  select t).IsExists(metaup))
            {
                return new
                {
                    code = "failed",
                    msg = "词典表不存在",
                };
            }
            dynamic info = list.First();
            string tablename = info.dic_name;
            var istree = BoolStd.IsNotBoolThen(info.istree);
            var datalist = (IEnumerable<object>)data;
            foreach (FrameDLRObject item in data)
            {
                if ((from t in DB.LamdaTable(up, tablename, "a")
                     where t.code == item.GetValue("code")
                     select t).IsExists(up))
                {
                    return new
                    {
                        code = "failed",
                        msg = "数据重复，不能继续进行操作",
                    };
                }
            }
            foreach (FrameDLRObject item in data)
            {
                if (istree)
                {
                    DB.QuickInsert(up, tablename, new
                    {
                        code = item.GetValue("code"),
                        value = item.GetValue("value"),
                        level = item.GetValue("level"),
                        p_code = item.GetValue("p_code"),
                        sort_no = IntStd.IsNotIntThen(item.GetValue("sort_no"), 0)
                    });
                }
                else
                {
                    DB.QuickInsert(up, tablename, new
                    {
                        code = item.GetValue("code"),
                        value = item.GetValue("value"),
                        sort_no = IntStd.IsNotIntThen(item.GetValue("sort_no"), 0)
                    });
                }
            }
            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
        [ActionAuth("MetaData")]
        [EWRAEmptyValid("code")]
        [EWRARouteDesc("删除词典表中的数据")]
        [EWRAAddInput("id", "string", "元数据表uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAAddInput("code", "string", @"待删除的数据编号，多个编号用逗号分隔", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAOutputDesc("返回结果", @"根据http的状态码来识别，204标识操作成功，404表示操作识别未找到删除的资料")]
        public override bool delete(string id)
        {
            var code = ComFunc.nvl(PostDataD.code);

            var metaup = DB.NewMetaUnitParameter();
            var up = DB.NewDBUnitParameter();

            var s = from t in DB.LamdaTable(metaup, "EXTEND_DICTIONARY_TABLE", "a")
                    where (t.dic_uid == id || t.dic_name == id) && t.IsCreated == 1
                    select t;
            var list = s.GetQueryList(metaup);
            if (!s.IsExists(metaup))
            {
                return false;
            }
            dynamic info = list.First();
            string tablename = info.dic_name;
            (from t in DB.LamdaTable(up, tablename, "a")
             where t.code.within(code)
             select t).Delete(up);

            return true;
        }
        [ActionAuth("MetaData")]
        [EWRAEmptyValid("data")]
        [EWRARouteDesc("修改词典表中的数据")]
        [EWRAAddInput("id", "string", "元数据表uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAAddInput("data", "array", @"待修改的数据列表，格式:
[
{
    code:'值',
    value:'值',
    level:'树结构中的层级,只有istree==true时候才有栏位',
    p_code:'父节点编号,只有istree==true时候才有栏位',
    sort_no:'排序'
}
]", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        public override object patch(string id)
        {
            var data = PostDataD.data;
            if (!(data is IEnumerable<object>))
            {
                return new
                {
                    code = "failed",
                    msg = "数据格式不正确"
                };
            }
            var metaup = DB.NewMetaUnitParameter();
            var up = DB.NewDBUnitParameter();

            var s = from t in DB.LamdaTable(metaup, "EXTEND_DICTIONARY_TABLE", "a")
                    where (t.dic_uid == id || t.dic_name == id) && t.IsCreated == 1
                    select t;
            var list = s.GetQueryList(metaup);
            if (!(from t in DB.LamdaTable(metaup, "EXTEND_DICTIONARY_TABLE", "a")
                  where (t.dic_uid == id || t.dic_name == id) && t.IsCreated == 1
                  select t).IsExists(metaup))
            {
                return new
                {
                    code = "failed",
                    msg = "词典表不存在",
                };
            }
            dynamic info = list.First();
            string tablename = info.dic_name;
            var istree = BoolStd.IsNotBoolThen(info.istree);
            var datalist = (IEnumerable<object>)data;

            foreach (FrameDLRObject item in data)
            {
                DB.QuickDelete(up, tablename, new
                {
                    code = item.GetValue("code")
                });
                if (istree)
                {
                    DB.QuickInsert(up, tablename, new
                    {
                        code = item.GetValue("code"),
                        value = item.GetValue("value"),
                        level = item.GetValue("level"),
                        p_code = item.GetValue("p_code"),
                        sort_no = IntStd.IsNotIntThen(item.GetValue("sort_no"), 0)
                    });
                }
                else
                {
                    DB.QuickInsert(up, tablename, new
                    {
                        code = item.GetValue("code"),
                        value = item.GetValue("value"),
                        sort_no = IntStd.IsNotIntThen(item.GetValue("sort_no"), 0)
                    });
                }
            }
            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
        /// <summary>
        /// 根据词典表的id或名称获取词典数据
        /// </summary>
        /// <param name="metaup"></param>
        /// <param name="up"></param>
        /// <param name="id"></param>
        /// <returns>普通数据集结构为[{code:'值',value:'显示用的信息'}]，如果为树结构[{code:'值',value:'显示用的信息',level:'层级',p_code:'父节点'}]</returns>
        public List<object> GetDictionaryDataList(UnitParameter metaup, UnitParameter up, string id)
        {
            var s = from t in DB.LamdaTable(metaup, "EXTEND_DICTIONARY_TABLE", "a")
                    where (t.dic_uid == id || t.dic_name == id) && t.IsCreated == 1
                    select t;
            var list = s.GetQueryList(metaup);
            if (list.Count <= 0)
            {
                return new List<object>();
            }
            dynamic info = list.First();
            string tablename = info.dic_name;
            var data = (from t in DB.LamdaTable(up, tablename, "a")
                        orderby t.sort_no
                        select t).GetQueryList(up);
            if (BoolStd.IsNotBoolThen(info.istree))
            {
                return (from t in data
                        select new
                        {
                            t.code,
                            t.value
                        }).ToList<object>();
            }
            else
            {
                return (from t in data
                        select new
                        {
                            t.code,
                            t.value,
                            t.p_code,
                            t.level
                        }).ToList<object>();
            }
        }
    }
}
